package cn.xiaopengstack.domain.rebate.service;

import cn.xiaopengstack.domain.award.model.valobj.TaskStateVO;
import cn.xiaopengstack.domain.rebate.event.SendBehaviorRebateEvent;
import cn.xiaopengstack.domain.rebate.model.aggregate.BehaviorRebateAggregate;
import cn.xiaopengstack.domain.rebate.model.entity.BehaviorEntity;
import cn.xiaopengstack.domain.rebate.model.entity.BehaviorRebateOrderEntity;
import cn.xiaopengstack.domain.rebate.model.entity.DailyBehaviorRebateEntity;
import cn.xiaopengstack.domain.rebate.repository.IBehaviorRebateRepository;
import cn.xiaopengstack.domain.task.model.TaskEntity;
import cn.xiaopengstack.types.common.Constants;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author jiangyangang
 */
@Service
@Slf4j
public class BehaviorRebateService implements IBehaviorRebateService{

    @Resource
    private IBehaviorRebateRepository behaviorRebateRepository;

    @Override
    public List<String> createOrder(BehaviorEntity behaviorEntity) {
        // 查询行为的配置
        List<DailyBehaviorRebateEntity> dailyBehaviorRebateEntities = behaviorRebateRepository.queryDailyBehaviorRebateListByType(behaviorEntity.getBehaviorTypeVO().getCode());
        if (CollectionUtils.isEmpty(dailyBehaviorRebateEntities)) {
            return Collections.emptyList();
        }
        List<String> orders = new ArrayList<>();
        List<BehaviorRebateAggregate> aggregates = new ArrayList<>();
        for (DailyBehaviorRebateEntity rebateEntity : dailyBehaviorRebateEntities) {
            String bizId = behaviorEntity.getUserEntity().getUserId() + Constants.UNDERLINE + rebateEntity.getRebateType() + Constants.UNDERLINE + behaviorEntity.getOutBusinessNo();

            String orderId = RandomStringUtils.randomNumeric(12);
            BehaviorRebateOrderEntity orderEntity = BehaviorRebateOrderEntity.builder()
                    .dailyBehaviorRebateEntity(rebateEntity)
                    .bizId(bizId)
                    .orderId(orderId)
                    .userEntity(behaviorEntity.getUserEntity())
                    .build();

            // 发送MQ
            SendBehaviorRebateEvent<SendBehaviorRebateEvent.SendBehaviorRebateMessage> event = new SendBehaviorRebateEvent<>(SendBehaviorRebateEvent.SendBehaviorRebateMessage
                    .builder()
                    .rebateConfig(rebateEntity.getRebateConfig())
                    .bizId(bizId)
                    .userId(behaviorEntity.getUserEntity().getUserId())
                    .rebateDesc(rebateEntity.getRebateDesc())
                    .rebateType(rebateEntity.getRebateType())
                    .behaviorTime(behaviorEntity.getBehaviorTime())
                    .build(), bizId);

            // 本地事务任务
            TaskEntity taskEntity = TaskEntity.builder()
                    .topic(event.topic())
                    .messageId(event.payload().getId())
                    .state(TaskStateVO.create)
                    .user(behaviorEntity.getUserEntity())
                    .message(JSONObject.toJSONString(event.getMessage()))
                    .build();

            // 构建聚合体
            BehaviorRebateAggregate aggregate = BehaviorRebateAggregate.builder()
                    .dailyBehaviorRebateEntity(rebateEntity)
                    .taskEntity(taskEntity)
                    .orderEntity(orderEntity)
                    .event(event)
                    .build();

            orders.add(orderId);
            aggregates.add(aggregate);
        }

        behaviorRebateRepository.saveDailyRebateOrder(aggregates);
        return orders;
    }

    @Override
    public List<BehaviorRebateOrderEntity> queryOrderByOutBusinessNo(String userId, String businessNo) {
        return behaviorRebateRepository.queryOrderByOutBusinessNo(userId, businessNo);
    }
}
